package com.sm.li.transfer.base;

import com.sm.li.utils.ReflectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

//属性转换
@Slf4j
public class BaseTransfer<DTO, Entity> {



    //entity转DTO
    public DTO toDTO(Entity entity) {
        //通过反射机制获取泛型的类类型
        try {
            Class<DTO> entityClass = (Class<DTO>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            DTO dto = entityClass.newInstance();
            BeanUtils.copyProperties(entity, dto);
            return dto;
        } catch (Exception e) {
            log.error("实体类转换DTO错误"+e.getMessage());
            return null;
        }
    }
    //集合形式entity转DTO
    public List<DTO> toDTO(List<Entity> list) {
        //通过反射机制获取泛型的类类型
        List<DTO> dtoList = new ArrayList<>();
        list.forEach(entity -> dtoList.add(toDTO(entity)));
        return dtoList;
    }


    //DTO转entity
    public Entity toEntity(DTO dto) {
        try {
            Class<Entity> entityClass = (Class<Entity>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
            Entity entity = entityClass.newInstance();
            BeanUtils.copyProperties(dto, entity);
            return entity;
        } catch (Exception e) {
            log.error("DTO转换实体类错误"+e.getMessage());
            return null;
        }
    }
    //集合形式DTO转entity
    public List<Entity> toEntity(List<DTO> list) {
        List<Entity> entityList = new ArrayList<>();
        list.forEach(dto -> entityList.add(toEntity(dto)));
        return entityList;
    }


}
